package com.threeox.commonlibrary.ui.view.engineview.model;

import android.content.Context;
import android.content.Intent;
import android.os.Message;
import android.util.AttributeSet;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;

import com.alibaba.fastjson.JSONObject;
import com.threeox.commonlibrary.R;
import com.threeox.commonlibrary.callback.CommonCallback;
import com.threeox.commonlibrary.entity.engine.ReloadType;
import com.threeox.commonlibrary.entity.engine.model.layout.CommandMsg;
import com.threeox.commonlibrary.entity.engine.model.layout.ModelMessage;
import com.threeox.commonlibrary.entity.engine.model.layout.ViewDataMsg;
import com.threeox.commonlibrary.entity.engine.request.base.BaseRequestMsg;
import com.threeox.commonlibrary.inter.event.OnEventListener;
import com.threeox.commonlibrary.inter.OnRequestListener;
import com.threeox.commonlibrary.ui.view.ModelButton;
import com.threeox.commonlibrary.ui.view.engineview.base.CommonModelView;
import com.threeox.commonlibrary.ui.view.inter.engine.base.IBaseExtend;
import com.threeox.commonlibrary.ui.view.inter.engine.model.IModelExtend;
import com.threeox.commonlibrary.ui.view.inter.multipage.IMultiPageView;
import com.threeox.commonlibrary.util.ActivityUtils;
import com.threeox.commonlibrary.util.ValueUtils;
import com.threeox.commonlibrary.util.engine.ControlFactory;
import com.threeox.commonlibrary.util.request.RequestHelper;
import com.threeox.utillibrary.util.EmptyUtils;
import com.threeox.utillibrary.util.LogUtils;
import com.threeox.utillibrary.util.res.LayoutUtils;
import com.threeox.utillibrary.util.thread.ThreadUtil;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import static android.view.ViewGroup.LayoutParams.MATCH_PARENT;
import static android.view.ViewGroup.LayoutParams.WRAP_CONTENT;

/**
 *
 * @ClassName: ModelBaseView
 *
 * @Description: (模型基础View)
 *
 * @author 赵屈犇
 *
 * @date 创建时间:2016/12/19 下午8:42
 *
 * @version 1.0
 */
public class ModelBaseView extends CommonModelView implements View.OnClickListener, OnEventListener {

    protected ScrollView mModelScrollView;
    // 模型VIew容器               命令按鈕View容器
    protected LinearLayout mModelLayout, mCommandLayout;
    protected IModelExtend mModelExtend;//模型的扩展类
    protected ControlFactory mFactory;// 创造View的工厂
    protected ModelMessage mModelMessage;// 模型对象的实体类
    protected RequestHelper mRequestHelper;

    /*=====================一些基本的常量声明======================*/
    protected final int PARSEREQUESTSUCCESS = 0x100000;// 请求数据成功之后并且解析完成的标志
    /*=====================一些基本的常量声明======================*/

    public ModelBaseView(Context context) {
        this(context, null);
    }

    public ModelBaseView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public ModelBaseView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    @Override
    protected void init() {
        super.init();
        mRequestHelper = RequestHelper.newInstance().setOnRequestListener(new OnResultRequestListener());
    }

    /**
     * 初始化数据
     *
     * @param intent
     * @return
     */
    @Override
    public void initData(Intent intent) {
        super.initData(intent);
        mRequestHelper.setIntent(intent);
        if (mModelMessage != null) {
            setBaseModelMsg(mModelMessage);
            initLayout();
            initCommandRequest();
            fillInView();
            initRequestMsg();
            initExtend();
            initPublic();
            execRequestMsg();
        }
    }

    @Override
    public ModelMessage initModelMessage(int fileName) {
        if (mModelMessage == null) {
            mFileName = fileName;
            if (mFileName == -1){
                LogUtils.e(TAG, NOTMODELFILE);
                return null;
            }
            mModelMessage = mCommonConfig.getModelMessage(mFileName);
        }
        return mModelMessage;
    }

    /**
     * 初始化View
     */
    private void initLayout() {
        if (mModelMessage.isScrollView()) {
            LayoutUtils.inflate(mContext, R.layout.view_model_base, this);
            mModelLayout = findViewById(R.id.id_model_layout);
            mContainerLayout = findViewById(R.id.id_model_container);
            mModelScrollView = findViewById(R.id.id_model_base_scroll);
        } else {
            mContainerLayout = new RelativeLayout(mContext);
            mContainerLayout.setId(R.id.id_model_container);
            mContainerLayout.setLayoutParams(new LayoutParams(MATCH_PARENT, MATCH_PARENT));
            this.addView(mContainerLayout);
            mModelLayout = new LinearLayout(mContext);
            mModelLayout.setId(R.id.id_model_layout);
            mModelLayout.setLayoutParams(new RelativeLayout.LayoutParams(MATCH_PARENT, MATCH_PARENT));
            mModelLayout.setOrientation(VERTICAL);
            mContainerLayout.addView(mModelLayout);
        }
        initScrollView();
        mFactory = ControlFactory.newInstance(mModelLayout, mCommandLayout, mContext);
    }

    /**
     * 初始化滚动布局
     */
    private void initScrollView() {
        if (mModelScrollView != null) {
            mModelScrollView.setVerticalScrollBarEnabled(mModelMessage.isShowVerticalScrollBar());
        }
    }

    /**
     * 填充所有的View
     */
    private void fillInView() {
        initCommonView();
        mFactory.fillInView(mModelMessage.getViewDataMsgs(), mIntent);// 初始化所有的模型View
        // 初始化CommandView 布局
        mCommandLayout = new LinearLayout(mContext);
        LayoutParams commandParams = new LayoutParams(MATCH_PARENT, WRAP_CONTENT);
        mCommandLayout.setLayoutParams(commandParams);
        mCommandLayout.setId(R.id.id_model_command_layout);
        mCommandLayout.setGravity(Gravity.CENTER_HORIZONTAL);
        mCommandLayout.setOrientation(LinearLayout.VERTICAL);
        mModelLayout.addView(mCommandLayout);
        // 初始化CommandView 布局
        mFactory.fillInCommand(mModelMessage.getCommandMsgs(), this);// 初始化所有的模型按鈕
    }

    /**
     * 请求数据
     */
    public void execRequestMsg() {
        if (mModelMessage.isExecute()) {
            if (null != mRequestMsg && mRequestMsg.isEmpty()) {
                requestIn();
                mModelLayout.setVisibility(View.GONE);
            }
            if (mModelExtend != null) {
                if (!mModelExtend.onBeforeExecRequest(mRequestMsg)) {
                    return;
                }
            }
            mRequestHelper.execRequest(mRequestMsg);
        }
    }

    @Override
    protected void initExtend() {
        try {
            if (mBaseExtend != null && mBaseExtend instanceof IModelExtend) {
                this.mModelExtend = (IModelExtend) mBaseExtend;
                mModelExtend.init(mContext, this);
            }
        } catch (Exception e) {
            LogUtils.e(TAG, e.getMessage());
        }
    }

    /**
     * 初始化Command请求对象
     */
    private void initCommandRequest() {
        List<CommandMsg> commandMsgs = mModelMessage.getCommandMsgs();
        if (EmptyUtils.isNotEmpty(commandMsgs)) {
            for (CommandMsg commandMsg: commandMsgs) {
                commandMsg.initAllParams(mIntent);
            }
        }
    }

    @Override
    public void onClick(View v) {
        if (v instanceof ModelButton) {
            CommandMsg commandMsg = ((ModelButton) v).getCommandMsg();
            onCommand(v, commandMsg);
        }
    }

    /**
     * 命令事件操作事件
     *
     * @param v
     * @param commandMsg
     */
    private void onCommand(View v, CommandMsg commandMsg) {
        JSONObject params = getValue();
        if (!verify(params)) {
            return;
        }
        try {
            if (mModelExtend != null && !mModelExtend.onBeforeCommand(commandMsg.getRequestMsg(), commandMsg, params)) {
                return;
            }
        } catch (Exception e) {
            LogUtils.e(TAG, "扩展类的onBeforeCommand函数报错了:" + e.getMessage());
            return;
        }
    }

    @Override
    public JSONObject getValue() {
        JSONObject params = super.getValue();
        List<ViewDataMsg> viewDataMsgs = mModelMessage.getViewDataMsgs();
        if (EmptyUtils.isNotEmpty(viewDataMsgs)){
            for (ViewDataMsg viewDataMsg : viewDataMsgs) {
                String tag = viewDataMsg.getViewTag();
                Object val = mViewUtils.getViewVal(this, tag);
                if (EmptyUtils.isNotEmpty(val)) {
                    params.put(tag, val);
                }
            }
        }
        return params;
    }

    @Override
    protected boolean verify(JSONObject value) {
        return mVerifyFactory.verify(mModelMessage.getVerifyMsgs(), value);
    }

    @Override
    public void onClick(View v, ReloadType reloadType) {
        super.onClick(v, reloadType);
        execRequestMsg();
    }

    public ModelMessage getModelMessage() {
        return mModelMessage;
    }

    public LinearLayout getModelLayout() {
        return mModelLayout;
    }

    /**
     * 请求结果响应的事件
     */
    class OnResultRequestListener implements OnRequestListener {

        @Override
        public void onSuccess(final BaseRequestMsg requestMsg, final String url, final int id, final String msg, final Object data) {
            boolean isIntercept = true;
            if (null != mModelExtend) {
                isIntercept = mModelExtend.onBeforeRequestSuccess(requestMsg, url, id, msg, data);
            }
            if (isIntercept && EmptyUtils.isNotEmpty(data)) {
                ThreadUtil.runInThread(new Runnable() {
                    @Override
                    public void run() {
                        Object result = data;
                        if (EmptyUtils.isNotEmpty(data)) {
                            if (data instanceof List) {
                                result = ((List) data).get(0);
                            }
                        }
                        if (EmptyUtils.isNotEmpty(getAllViewTags())) {
                            Map<Object, Object> results = new HashMap<Object, Object>();
                            for (Object tag : getAllViewTags()) {
                                try {
                                    if (EmptyUtils.isNotEmpty(tag)) {
                                        results.put(tag, ValueUtils.getObjValue(result, String.valueOf(tag)));
                                    }
                                } catch (Exception e) {
                                    LogUtils.e(TAG, "初始化ViewVal出错了:" + e.getMessage());
                                }
                            }
                            sendViewValue(results);
                        }
                        putRequestResult(requestMsg.getKey(), result);
                        sendAfterSuccess(requestMsg, url, id, msg, result);
                    }
                });
            } else {
                sendAfterSuccess(requestMsg, url, id, msg, data);
            }
        }

        @Override
        public void onError(BaseRequestMsg requestMsg, String url, int id, Object code, String msg, Object data) {
            if (RequestHelper.NOTNETWORKCONNECTED.equals(String.valueOf(code))) {
                networkClose(mModelMessage.getNotNetWorkMessage());
            } else if (CommonCallback.NOTDATAERRORCODE.equals(String.valueOf(code))) {
                notData(msg);
            } else {
                requestFault(code, msg);
            }
            if (mModelMessage.isShowErrorToast()) {
                showToast(msg);
            }
            if (null != mModelExtend) {
                mModelExtend.onRequestError(requestMsg, url, id, code, msg);
            }
        }

        @Override
        public void inProgress(BaseRequestMsg requestMsg, float progress, long total, int id, String url) {
            if (mModelExtend != null) {
                mModelExtend.onRequestInProgress(requestMsg, progress, total, id, url);
            }
        }

        /**
         * 发送 请求数据成功之后，解析和注入数据之后调用 回调请求
         *
         * @param requestMsg
         * @param url
         * @param id
         * @param msg
         * @param data
         */
        private void sendAfterSuccess(BaseRequestMsg requestMsg, String url, int id, String msg, Object data) {
            Map<String, Object> map = new HashMap<>();
            map.put("id", id);
            map.put("url", url);
            map.put("msg", msg);
            map.put("data", data);
            map.put("requestMsg", requestMsg);
            mHandlerUtils.putWhat(PARSEREQUESTSUCCESS).put(map).send();
        }
    }

    /**
     * Handler 的回调函数
     *
     * @param message
     */
    @Override
    public void onHandleMessage(Message message) throws Exception {
        super.onHandleMessage(message);
        int what = message.what;
        if (PARSEREQUESTSUCCESS == what) {// 请求数据成功之后并且解析完成的标志
            Map<String, Object> result = (Map<String, Object>) message.obj;
            int id = (int) result.get("id");
            Object data = result.get("data");
            String url = String.valueOf(result.get("url"));
            String msg = String.valueOf(result.get("msg"));
            BaseRequestMsg requestMsg = (BaseRequestMsg) result.get("requestMsg");
            if (EmptyUtils.isNotEmpty(data)) {
                requestSucceed(data);
                mModelLayout.setVisibility(View.VISIBLE);
            } else {
                notData(EmptyUtils.isNotEmpty(msg) ? msg : mModelMessage.getNotDataMessage());
                mModelLayout.setVisibility(View.GONE);
            }
            if (null != mModelExtend)
                mModelExtend.onAfterRequestSuccess(requestMsg, url, id, msg, data);
        }
    }
}
